import { useCallback, useEffect, useState } from 'react';
import { Button, List, Switch, Tag, Toast, Popup, Form, Input, Selector } from 'antd-mobile';
import Requests from '../shared/RestUtils';
import Channels from '../shared/Channels';

function formalizeUrl(domainName) {
    const channel = localStorage.getItem('channel');
    const channelInfo = Channels.find(c => c.value === channel);

    if (channelInfo !== undefined) {
        return `https://${domainName}.${channelInfo.portal}`;
    }
    return domainName;
}

const genderOptions = [
    {
        'label': 'Female',
        'value': 'female'
    },
    {
        'label': 'Male',
        'value': 'male'
    }
]

function Tenants() {
    const [tenants, setTenants] = useState([]);

    const [channel, setChannel] = useState('');

    const [bottomSheetVisible, setBottomSheetVisible] = useState(false);

    const reloadTenants = useCallback(() => {
        Requests.current().getTenants().then(result => {
            setTenants(result);
        });
    }, []);

    const openBottomSheet = useCallback(() => {
        setBottomSheetVisible(true);
    }, []);

    const onTenantEnableChanged = useCallback(i => {
        return v => {
            Requests.current().enableTenant(i, v).then(() => {
                reloadTenants();
            }).catch(() => {
                Toast.show(`${v ? 'enable' : 'disable'} domain failed`);
            });
        };
    }, [reloadTenants]);

    const onNewTenantSubmit = useCallback(({ name, domainName, username, gender, phoneNumber }) => {
        const newTenant = {
            name, domainName, adminUser: {
                name: username,
                gender: gender[0],
                phoneNumber
            }
        };

        Requests.current().createNewTenant(newTenant).then(() => {
            reloadTenants();
            setBottomSheetVisible(false);
        }).catch(() => {
            Toast.show(`create new tenant failed`);
        });
    }, [setBottomSheetVisible, reloadTenants]);

    useEffect(() => {
        setChannel(localStorage.getItem('channel'));
        reloadTenants();
    }, [reloadTenants, setChannel])

    return (
        <>
            <h1 className="title">All Tenants <Tag color="primary">{channel}</Tag></h1>
            <Button color='primary' style={{ margin: 8 }} onClick={openBottomSheet}>Add New Tenant</Button>
            <List>
                {
                    tenants.sort((t1, t2) => t2.createTime - t1.createTime)
                        .map(t => Object.assign(t, { domain: formalizeUrl(t.domainName) }))
                        .map(t => (
                            <List.Item key={t.id}
                                description={t.domain}
                                title={new Date(t.updateTime || t.createTime).toDateString()}
                                extra={
                                    <Switch uncheckedText='Off' checkedText='On' checked={t.enabled} onChange={onTenantEnableChanged(t.id)} />
                                }>
                                <a href={t.domain} alt={t.domain} target={t.domain}>{t.name}</a>
                            </List.Item>
                        ))
                }
            </List>
            <Popup
                visible={bottomSheetVisible}
                onMaskClick={() => {
                    setBottomSheetVisible(false)
                }}
                bodyStyle={{ minHeight: '40vh' }}
            >
                <Form
                    onFinish={onNewTenantSubmit}
                    footer={
                        <Button block type='submit' color='primary'>
                            Submit
                        </Button>
                    }
                >
                    <Form.Item
                        name='name'
                        label='Tenant Name'
                        rules={[{ required: true, message: 'tenant name cannot be null' }]}
                    >
                        <Input placeholder='Input Tenant Name' />
                    </Form.Item>
                    <Form.Item
                        name='domainName'
                        label='Domain Name'
                        rules={[{ required: true, message: 'domain name cannot be null' }]}>
                        <Input placeholder='Input Domain Name' />
                    </Form.Item>
                    <Form.Item
                        name='username'
                        label='Username'
                        rules={[{ required: true, message: 'username cannot be null' }]}>
                        <Input placeholder='Input Username' />
                    </Form.Item>
                    <Form.Item
                        name='phoneNumber'
                        label='Phone Number'
                        rules={[{ required: true, message: 'phone number cannot be null' }]}>
                        <Input placeholder='Input Phone Number' />
                    </Form.Item>
                    <Form.Item
                        name='gender'
                        label='Gender'
                        initialValue={['female']}
                        rules={[{ required: true }]}>
                        <Selector options={genderOptions}></Selector>
                    </Form.Item>
                </Form>
            </Popup>
        </>
    );
}

export default Tenants;